package org.jactao.remote.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.jactao.serialization.LSerializer;

/**
 * Created by fanzetao on 2018/4/3.
 */
public class NettyEncoder extends MessageToByteEncoder {

    private LSerializer serializer;

    public NettyEncoder serializer(LSerializer serializer) {
        this.serializer = serializer;
        return this;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        try {
            byte[] content = serializer.serialize(o);
            byteBuf.writeShort(content.length);
            byteBuf.writeBytes(content);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
